package org.song.util;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.song.exception.myException.CommonException;

/**
 * Jackson解析工具类，springboot框架中的web模块会自动集成jackson解析器
 */
public final class JacksonUtil {
    private JacksonUtil() {}

    private static final ObjectMapper OBJECT_MAPPER = new ObjectMapper();

    /**
     * 解析对象为JSON字符串
     * @param obj
     * @return
     * @throws JsonProcessingException
     */
    public static String getJsonString(Object obj) {
        if (obj == null) {
            return null;
        }
        try {
            return OBJECT_MAPPER.writeValueAsString(obj);
        } catch (JsonProcessingException e) {
            throw new CommonException( e.getMessage() );
        }
    }

    /**
     * 获取JSON字符串对应的java对象
     * @param jsonStr
     * @param objectClass
     * @return
     * @throws JsonProcessingException
     */
    public static Object getObject(String jsonStr , Class<? super Object> objectClass) throws JsonProcessingException {
        if (jsonStr == null) {
            return null;
        }
        return OBJECT_MAPPER.readValue(jsonStr, objectClass);
    }
}
